<template>
    <el-dialog v-model="state.isShowDialog" width="1100px" @close='closeDialog'>
        <el-table ref="multipleTable" :data="state.pageData.currentData" tooltip-effect="dark" style="width: 100%" :row-style="{height: '0'}" :cell-style="{padding:5+'px'}"
            @selection-change="handleSelectionChange" :row-key="rowKey">
            <el-table-column type="selection" width="40" prop="apiRoute" :reserve-selection="true"></el-table-column>
            <el-table-column  label="资源" prop="apiRoute" width="280">
            </el-table-column>           
            <el-table-column label="数据范围" prop="dataScopeType" width="640"  show-overflow-tooltip :rules="[{ required: true, message: '数据范围不能为空'}]">  
                <template #default="scope">
                    <el-radio-group v-model="scope.row.dataScopeType" @change="changeDataScope(scope.row)">
                        <el-radio v-for="d in props.dataScope" :key="d.value" :label="d.value" >{{d.name}}</el-radio>
                    </el-radio-group>                                        															
                </template>
            </el-table-column>  
            <el-table-column show-overflow-tooltip>
                <template #default="scope">
                    <el-button v-if="scope.row.dataScopeType==='DataScopeDefine'" type="primary" size="default" text @click="choiceOrg(scope.row)">选择机构</el-button>
                </template>
            </el-table-column>         
        </el-table>
        <el-pagination
            :page-size="state.pageData.pageSize"
            :total="state.pageData.totalCount"
            @current-change="handleCurrentChange"
		/>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog" size="default">{{$t('message.userOperation.cancel')}}</el-button>
                <el-button type="primary" @click="submit" size="default">{{$t('message.userOperation.submit')}}</el-button>
            </span>
        </template>
        <defineOrg ref="defineOrgRef" @backData="backData"/>
    </el-dialog>
</template>
<script setup lang="ts">
import { reactive, toRaw ,ref} from 'vue';
import { ResourceOutput, SysDictData } from '/@/api-services/models/system';
import { feature } from "/@/utils/axios-utils";
import { ElMessage } from 'element-plus';
import defineOrg from './defineOrg.vue';
import roleApi from '/@/api-services/apis/system/roleApi';
const defineOrgRef=ref();
const multipleTable=ref();
const props = defineProps({
	dataScope: Array<SysDictData>
});
const state = reactive({
    loading: false,
    isShowDialog: false,
    title: '',
    roleId: 0,
    resourceData: [] as Array<ResourceOutput>,//该角色对应资源列表
    selected:[] as Array<ResourceOutput>,//已选择数据
    dataScope:'',//角色数据范围
    defineScopeOrgList:[] as Array<number> | null,//自定义数据范围
    pageData: {
        totalCount: 0,
        pageIndex: 1,
        pageSize: 10,
        currentData: [] as Array<ResourceOutput>
    }
});
const rowKey=(row:any)=>{
    return row.apiRoute;
}

//val:所有已选中数据
const handleSelectionChange=(val:Array<ResourceOutput>) =>{            
    state.resourceData.forEach(item=>{       
        //如果没有选中，那么设置为‘’
        var indexCurSelected= val.findIndex(it=>it.apiRoute===item.apiRoute);       
        if(indexCurSelected==-1){
            item.dataScopeType='';
            item.defineScopeOrgList=[];
            return;
        }
        //如果当前行被选中，那么判断是否在已选中数据中，
        //如果在，那么不用修改
        //如果不在，那么设置为角色对应数据范围
        var indexSelected= state.selected.findIndex(it=>item.apiRoute===it.apiRoute); 
        if(indexSelected>-1)return;
        item.dataScopeType=state.dataScope;            
        item.defineScopeOrgList=state.defineScopeOrgList;
    })
    state.selected=val;
}
const changeDataScope= (row:ResourceOutput)=>{
    var indexSelected= state.selected.findIndex(item=>item.apiRoute===row.apiRoute);  
    if(indexSelected>-1){
        state.selected[indexSelected].dataScopeType=row.dataScopeType;
        if(row.dataScopeType!=='DataScopeDefine'){
            state.selected[indexSelected].defineScopeOrgList=[];
        }
    }
}
const openDialog=async(row:any)=>{
    state.isShowDialog=true;
    handleDataScope();
    //根据角色查询资源
    var resourceRes=await roleApi.getResource({id:row.id});
    //查询已分配资源
    const ownResourceRes =await roleApi.getOwnResource({id:row.id}); 
    //记录角色数据范围
    state.roleId=row.id;
    state.dataScope=row.dataScope;   
    state.defineScopeOrgList=row.defineScopeOrgList;
    handelData(resourceRes.data.data,ownResourceRes.data.data.resources);
    state.pageData.pageIndex=1;
    state.pageData.totalCount=resourceRes.data.data.length;
    handleCurrentChange(state.pageData.pageIndex)//分页
}
//处理资源数据
const handelData=(resourceRes:Array<string>,ownResource:Array<ResourceOutput>)=>{
    resourceRes.forEach((api:string)=>{
        let obj:ResourceOutput = {
            apiRoute: api,
            dataScopeType: '' as any,
            defineScopeOrgList:[] as any
		}
        if (ownResource.length > 0) {
            var indexSelected= ownResource.findIndex((it:ResourceOutput)=>api===it.apiRoute); 
            if(indexSelected>-1){
                multipleTable.value.toggleRowSelection(ownResource[indexSelected],true)   
                obj.dataScopeType=ownResource[indexSelected].dataScopeType;
                obj.defineScopeOrgList = ownResource[indexSelected].defineScopeOrgList
            }            
        }
        state.resourceData.push(obj);
    })
}
const handleCurrentChange=(val:any)=>{
    state.pageData.pageIndex=val;
    state.pageData.currentData=state.resourceData.slice((val-1)*state.pageData.pageSize,val*state.pageData.pageSize);   
}
const handleDataScope=()=>{
    var dataScope=[] as any
    props.dataScope?.forEach(item=>{
        dataScope.push({name:item.name,value:item.value})
    })
    return dataScope;
}

const choiceOrg=(row:any)=>{
    defineOrgRef.value.openDialog(row)
}

const backData=(data:any)=>{
    var indexSelected= state.selected.findIndex((item:any)=>item.apiRoute===data.apiRoute);  
    if(indexSelected>-1){
        state.selected[indexSelected].defineScopeOrgList=toRaw(data.defineScopeOrgList);
    }
}
// 关闭弹窗
const closeDialog = () => {
    multipleTable.value.clearSelection();
	state.isShowDialog = false;
};

const submit=async()=>{
     var data=JSON.parse(JSON.stringify(state.selected));
     data.forEach((it:any)=>{
        if(it.dataScopeType!=='DataScopeDefine'){
            it.defineScopeOrgList=[];
        }
     });
     var input={id:state.roleId,resources:data};
     const [err]=await feature(roleApi.grantRoleResource(input));
     if(err){
        ElMessage.error(err.message)
     }
     else{
        closeDialog();
     }
};
// 导出对象
defineExpose({ openDialog });
</script>
